<template>
	<view class="profile-container">
		<!-- 头像区域 -->
		<view class="avatar-section">
			<view class="avatar-container" @click="changeAvatar">
				<view class="avatar-placeholder">
					<image v-if="userInfo.avatarUrl" :src="userInfo.avatarUrl" class="avatar-image" mode="aspectFill"></image>
					<uni-icons v-else type="person" size="60" color="#ccc"></uni-icons>
				</view>
				<text class="avatar-tip">点击修改头像</text>
			</view>
		</view>

		<!-- 信息字段区域 -->
		<view class="info-section">
			<!-- 昵称 -->
			<view class="info-item" @click="editNickname">
				<text class="item-label">昵称</text>
				<view class="item-value">
					<text class="value-text">{{ userInfo.memberName || '未设置' }}</text>
					<uni-icons type="right" size="16" color="#999"></uni-icons>
				</view>
			</view>

			<!-- 性别 -->
			<view class="info-item">
				<text class="item-label">性别</text>
				<view class="item-value">
					<view class="radio-group">
						<view class="radio-item" @click="selectGender('male')">
							<view class="radio-circle" :class="{ active: userInfo.gender === 'male' }"></view>
							<text class="radio-text">男</text>
						</view>
						<view class="radio-item" @click="selectGender('female')">
							<view class="radio-circle" :class="{ active: userInfo.gender === 'female' }"></view>
							<text class="radio-text">女</text>
						</view>
						<view class="radio-item" @click="selectGender('unknown')">
							<view class="radio-circle" :class="{ active: userInfo.gender === 'unknown' }"></view>
							<text class="radio-text">保密</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 生日 -->
			<view class="info-item" @click="selectBirthday">
				<text class="item-label">生日</text>
				<view class="item-value">
					<text class="value-text" :class="{ placeholder: !userInfo.birthday }">
						{{ formatBirthday(userInfo.birthday) || '请选择出生日期' }}
					</text>
					<uni-icons type="right" size="16" color="#999"></uni-icons>
				</view>
			</view>

			<!-- 地区 -->
			<view class="info-item" @click="selectCity">
				<text class="item-label">地区</text>
				<view class="item-value">
					<text class="value-text" :class="{ placeholder: !userInfo.region }">
						{{ userInfo.region || '请选择地区' }}
					</text>
					<uni-icons type="right" size="16" color="#999"></uni-icons>
				</view>
			</view>

			<!-- 手机号 -->
			<view class="info-item">
				<text class="item-label">手机号</text>
				<view class="item-value">
					<text class="value-text">{{ userInfo.contact || '未绑定' }}</text>
				</view>
			</view>

			<!-- 积分 -->
			<view class="info-item">
				<text class="item-label">积分</text>
				<view class="item-value">
					<text class="value-text">{{ userInfo.points || 0 }}</text>
				</view>
			</view>

			<!-- 注册时间 -->
			<view class="info-item">
				<text class="item-label">注册时间</text>
				<view class="item-value">
					<text class="value-text">{{ formatDate(userInfo.registerTime) }}</text>
				</view>
			</view>
		</view>

		<!-- 底部按钮区域 -->
		<view class="button-section">
			<view class="button-group">
				<view class="save-btn" @click="saveProfile">
					<text class="save-text">保存</text>
				</view>
				<view class="logout-btn" @click="logout">
					<text class="logout-text">退出登录</text>
				</view>
			</view>
		</view>

		<!-- 生日选择器弹窗 -->
		<u-popup :show="showBirthdayPicker" mode="bottom" @close="cancelBirthday">
			<view class="picker-container">
				<view class="picker-header">
					<text class="cancel-btn" @click="cancelBirthday">取消</text>
					<text class="confirm-btn" @click="confirmBirthday">确认</text>
				</view>
				<view class="picker-content">
					<view class="picker-column">
						<scroll-view scroll-y class="picker-scroll">
							<view 
								v-for="year in years" 
								:key="year"
								class="picker-item"
								:class="{ active: year === selectedYear + ' 年' }"
								@click="selectedYear = year.replace(' 年', '')"
							>
								{{ year }}
							</view>
						</scroll-view>
					</view>
					<view class="picker-column">
						<scroll-view scroll-y class="picker-scroll">
							<view 
								v-for="month in months" 
								:key="month"
								class="picker-item"
								:class="{ active: month === selectedMonth + ' 月' }"
								@click="selectedMonth = month.replace(' 月', '')"
							>
								{{ month }}
							</view>
						</scroll-view>
					</view>
					<view class="picker-column">
						<scroll-view scroll-y class="picker-scroll">
							<view 
								v-for="day in days" 
								:key="day"
								class="picker-item"
								:class="{ active: day === selectedDay + ' 日' }"
								@click="selectedDay = day.replace(' 日', '')"
							>
								{{ day }}
							</view>
						</scroll-view>
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 昵称编辑弹窗 -->
		<u-popup :show="showNicknameEdit" mode="center" @close="cancelNicknameEdit">
			<view class="nickname-edit-container">
				<view class="nickname-edit-header">
					<text class="nickname-edit-title">修改昵称</text>
					<view class="close-btn" @click="cancelNicknameEdit">
						<uni-icons type="close" size="20" color="#999"></uni-icons>
					</view>
				</view>
				<view class="nickname-edit-content">
					<input 
						v-model="tempNickname" 
						class="nickname-input" 
						placeholder="请输入昵称"
						maxlength="20"
						focus
					/>
					<text class="nickname-tip">最多20个字符</text>
				</view>
				<view class="nickname-edit-footer">
					<view class="nickname-btn cancel-nickname-btn" @click="cancelNicknameEdit">
						<text class="nickname-btn-text">取消</text>
					</view>
					<view class="nickname-btn confirm-nickname-btn" @click="confirmNicknameEdit">
						<text class="nickname-btn-text">确定</text>
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 城市选择器弹窗 -->
		<u-popup :show="showCityPicker" mode="bottom" @close="cancelCity">
			<view class="city-picker-container">
				<view class="city-picker-header">
					<text class="city-picker-title">区域选择</text>
					<view class="close-btn" @click="cancelCity">
						<uni-icons type="close" size="20" color="#999"></uni-icons>
					</view>
				</view>
				<view class="city-picker-tabs">
					<view class="tab-item active">
						<text class="tab-text">请选择</text>
					</view>
				</view>
				<view class="city-picker-content">
					<scroll-view scroll-y class="city-list">
						<view 
							v-for="province in Object.keys(cityData)" 
							:key="province"
							class="city-item"
							:class="{ active: province === selectedProvince }"
							@click="selectProvince(province)"
						>
							{{ province }}
						</view>
					</scroll-view>
					<scroll-view v-if="currentCities.length > 0" scroll-y class="city-list">
						<view 
							v-for="city in currentCities" 
							:key="city"
							class="city-item"
							:class="{ active: city === selectedCity }"
							@click="selectCityItem(city)"
						>
							{{ city }}
							<view v-if="city === selectedCity" class="check-icon">
								<uni-icons type="checkmarkempty" size="16" color="#4CAF50"></uni-icons>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import webSocketManager from '@/utils/websocket.js'

	export default {
		data() {
			return {
				userInfo: {
					memberId: '',
					memberUuid: '',
					memberName: '',
					avatarUrl: '',
					contact: '',
					registerTime: '',
					points: 0,
					roleId: 0,
					gender: 'unknown',
					birthday: '',
					region: '',
					lastLoginTime: '',
					isEnabled: 1,
					createdAt: '',
					updatedAt: ''
				},
				// 生日选择器相关
				showBirthdayPicker: false,
				selectedYear: '1990',
				selectedMonth: '01',
				selectedDay: '01',
				years: [],
				months: [],
				days: [],
				
				// 昵称编辑相关
				showNicknameEdit: false,
				tempNickname: '',
				
				// 城市选择器相关
				showCityPicker: false,
				selectedProvince: '',
				selectedCity: '',
				currentCities: [],
				cityData: {
					'广东省': ['广州市', '深圳市', '珠海市', '汕头市', '佛山市', '韶关市', '湛江市', '肇庆市', '江门市', '茂名市'],
					'辽宁省': ['沈阳市', '大连市', '鞍山市', '抚顺市', '本溪市', '丹东市', '锦州市', '营口市', '阜新市', '辽阳市'],
					'新疆维吾尔自治区': ['乌鲁木齐市', '克拉玛依市', '吐鲁番市', '哈密市', '昌吉回族自治州', '博尔塔拉蒙古自治州'],
					'河南省': ['郑州市', '开封市', '洛阳市', '平顶山市', '安阳市', '鹤壁市', '新乡市', '焦作市', '濮阳市'],
					'内蒙古自治区': ['呼和浩特市', '包头市', '乌海市', '赤峰市', '通辽市', '鄂尔多斯市', '呼伦贝尔市'],
					'湖北省': ['武汉市', '黄石市', '十堰市', '宜昌市', '襄阳市', '鄂州市', '荆门市', '孝感市', '荆州市'],
					'黑龙江省': ['哈尔滨市', '齐齐哈尔市', '鸡西市', '鹤岗市', '双鸭山市', '大庆市', '伊春市', '佳木斯市'],
					'上海市': ['黄浦区', '徐汇区', '长宁区', '静安区', '普陀区', '虹口区', '杨浦区', '闵行区', '宝山区']
				}
			}
		},
		methods: {
			// 格式化生日显示
			formatBirthday(birthday) {
				if (!birthday) return '';
				try {
					const date = new Date(birthday);
					return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
				} catch (error) {
					return birthday;
				}
			},

			// 格式化日期显示
			formatDate(dateString) {
				if (!dateString) return '';
				try {
					const date = new Date(dateString);
					return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
				} catch (error) {
					return dateString;
				}
			},

			// 修改头像
			changeAvatar() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						// 将选择的图片路径保存到用户信息中
						this.$set(this.userInfo, 'avatarUrl', res.tempFilePaths[0]);
						
						uni.showToast({
							title: '头像修改成功',
							icon: 'success'
						});
					},
					fail: (err) => {
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						});
					}
				});
			},

			// 编辑昵称
			editNickname() {
				this.tempNickname = this.userInfo.memberName;
				this.showNicknameEdit = true;
			},

			// 确认昵称编辑
			confirmNicknameEdit() {
				if (this.tempNickname.trim()) {
					// 使用 Vue.set 或直接赋值来确保响应式更新
					this.$set(this.userInfo, 'memberName', this.tempNickname.trim());
					
					this.showNicknameEdit = false;
					
					// 立即保存到本地存储
					uni.setStorageSync('userInfo', this.userInfo);
					
					uni.showToast({
						title: '昵称修改成功',
						icon: 'success'
					});
				} else {
					uni.showToast({
						title: '昵称不能为空',
						icon: 'none'
					});
				}
			},

			// 取消昵称编辑
			cancelNicknameEdit() {
				this.showNicknameEdit = false;
				this.tempNickname = '';
			},

			// 选择性别
			selectGender(gender) {
				this.$set(this.userInfo, 'gender', gender);
			},

			// 选择生日
			selectBirthday() {
				this.showBirthdayPicker = true;
			},

			// 选择城市
			selectCity() {
				this.showCityPicker = true;
			},

			// 确认生日选择
			confirmBirthday() {
				if (this.selectedYear && this.selectedMonth && this.selectedDay) {
					const birthday = `${this.selectedYear}-${this.selectedMonth}-${this.selectedDay}`;
					this.$set(this.userInfo, 'birthday', birthday);
				}
				this.showBirthdayPicker = false;
			},

			// 取消生日选择
			cancelBirthday() {
				this.showBirthdayPicker = false;
			},

			// 确认城市选择
			confirmCity() {
				if (this.selectedProvince && this.selectedCity) {
					this.$set(this.userInfo, 'region', `${this.selectedProvince} ${this.selectedCity}`);
				}
				this.showCityPicker = false;
			},

			// 取消城市选择
			cancelCity() {
				this.showCityPicker = false;
			},

			// 选择省份
			selectProvince(province) {
				this.selectedProvince = province;
				this.selectedCity = '';
				this.currentCities = this.cityData[province] || [];
			},

			// 选择城市
			selectCityItem(city) {
				this.selectedCity = city;
				// 选择城市后自动关闭选择器
				this.confirmCity();
			},

			// 初始化日期数据
			initDateData() {
				// 生成年份数据（1950-2024）
				for (let i = 1950; i <= 2024; i++) {
					this.years.push(i + ' 年');
				}
				
				// 生成月份数据
				for (let i = 1; i <= 12; i++) {
					this.months.push((i < 10 ? '0' + i : i) + ' 月');
				}
				
				// 生成日期数据
				for (let i = 1; i <= 31; i++) {
					this.days.push((i < 10 ? '0' + i : i) + ' 日');
				}
			},

			// 保存个人信息
			saveProfile() {
				uni.showLoading({
					title: '保存中...'
				});

				// 保存用户信息到本地存储
				uni.setStorageSync('userInfo', this.userInfo);

				// 强制更新页面显示
				this.$forceUpdate();
				
				// 使用 nextTick 确保 DOM 更新
				this.$nextTick(() => {
					// 重新加载用户信息以确保显示正确
					this.loadUserInfo();
				});

				setTimeout(() => {
					uni.hideLoading();
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					});
					
					// 返回上一页并刷新
					setTimeout(() => {
						uni.navigateBack({
							success: () => {
								// 通知上一页刷新数据
								const pages = getCurrentPages();
								if (pages.length > 1) {
									const prevPage = pages[pages.length - 2];
									if (prevPage && prevPage.loadLatestUserInfo) {
										prevPage.loadLatestUserInfo();
									}
								}
							}
						});
					}, 1000);
				}, 1500);
			},

			// 退出登录
			logout() {
				uni.showModal({
					title: '提示',
					content: '确定要退出登录吗？',
					success: (res) => {
						if (res.confirm) {
							// 关闭WebSocket连接
							console.log('退出登录，关闭WebSocket连接')
							webSocketManager.disconnect()
							
							// 清除登录状态
							uni.removeStorageSync('userInfo');
							uni.removeStorageSync('userToken');
							uni.removeStorageSync('token');
							uni.removeStorageSync('isLogin');
							
							uni.showToast({
								title: '已退出登录',
								icon: 'success'
							});
							
							// 返回上一页
							setTimeout(() => {
								uni.navigateBack();
							}, 1500);
						}
					}
				});
			}
		},
		
		// 生命周期钩子
		mounted() {
			this.initDateData();
			this.loadUserInfo();
		},
		
		// 页面加载时接收参数
		onLoad(options) {
			console.log('页面参数:', options);
			if (options.userInfo) {
				try {
					const userInfo = JSON.parse(decodeURIComponent(options.userInfo));
					console.log('接收到的用户信息:', userInfo);
					
					// 立即更新用户信息
					Object.keys(userInfo).forEach(key => {
						if (this.userInfo.hasOwnProperty(key)) {
							this.$set(this.userInfo, key, userInfo[key]);
						}
					});
					
					// 保存到本地存储
					uni.setStorageSync('userInfo', this.userInfo);
				} catch (error) {
					console.error('解析用户信息失败:', error);
				}
			}
		},
		
		// 页面显示时重新加载用户信息
		onShow() {
			// 延迟一点时间确保数据已经保存
			setTimeout(() => {
				this.loadUserInfo();
			}, 100);
		},

		// 加载用户信息
		loadUserInfo() {
			const savedUserInfo = uni.getStorageSync('userInfo');
			console.log('从本地存储读取的用户信息:', savedUserInfo);
			
			if (savedUserInfo) {
				// 逐个更新属性以确保响应式更新
				Object.keys(savedUserInfo).forEach(key => {
					if (this.userInfo.hasOwnProperty(key)) {
						this.$set(this.userInfo, key, savedUserInfo[key]);
					}
				});
				
				// 强制更新视图
				this.$forceUpdate();
				
				console.log('更新后的用户信息:', this.userInfo);
			}
		}
	}
</script>

<style scoped>
	.profile-container {
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	/* 头像区域 */
	.avatar-section {
		background-color: #fff;
		padding: 40rpx 0;
		text-align: center;
		margin-bottom: 20rpx;
	}

	.avatar-container {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.avatar-placeholder {
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
		background-color: #f0f0f0;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 20rpx;
		overflow: hidden;
	}

	.avatar-image {
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}

	.avatar-tip {
		font-size: 24rpx;
		color: #999;
	}

	/* 信息字段区域 */
	.info-section {
		background-color: #fff;
		margin-bottom: 20rpx;
	}

	.info-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.info-item:last-child {
		border-bottom: none;
	}

	.item-label {
		font-size: 28rpx;
		color: #333;
	}

	.item-value {
		display: flex;
		align-items: center;
	}

	.value-text {
		font-size: 28rpx;
		color: #333;
		margin-right: 10rpx;
	}

	.value-text.placeholder {
		color: #999;
	}

	/* 单选按钮样式 */
	.radio-group {
		display: flex;
		align-items: center;
	}

	.radio-item {
		display: flex;
		align-items: center;
		margin-right: 40rpx;
	}

	.radio-item:last-child {
		margin-right: 0;
	}

	.radio-circle {
		width: 32rpx;
		height: 32rpx;
		border-radius: 50%;
		border: 2rpx solid #ddd;
		margin-right: 10rpx;
		position: relative;
	}

	.radio-circle.active {
		border-color: #ff4444;
		background-color: #ff4444;
	}

	.radio-circle.active::after {
		content: '';
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 12rpx;
		height: 12rpx;
		border-radius: 50%;
		background-color: #fff;
	}

	.radio-text {
		font-size: 28rpx;
		color: #333;
	}

	/* 手机号绑定样式 */
	.phone-action {
		font-size: 28rpx;
		color: #ff4444;
	}

	/* 底部按钮区域 */
	.button-section {
		padding: 40rpx 20rpx;
	}

	.button-group {
		display: flex;
		gap: 20rpx;
	}

	.save-btn {
		flex: 1;
		height: 80rpx;
		background-color: #ff4444;
		border-radius: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.save-text {
		font-size: 32rpx;
		color: #fff;
		font-weight: 500;
	}

	.logout-btn {
		flex: 1;
		height: 80rpx;
		background-color: #fff;
		border: 2rpx solid #ff4444;
		border-radius: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.logout-text {
		font-size: 32rpx;
		color: #ff4444;
		font-weight: 500;
	}

	/* 生日选择器样式 */
	.picker-container {
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		overflow: hidden;
	}

	.picker-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.cancel-btn {
		font-size: 28rpx;
		color: #333;
	}

	.confirm-btn {
		font-size: 28rpx;
		color: #ff4444;
	}

	.picker-content {
		display: flex;
		height: 400rpx;
	}

	.picker-column {
		flex: 1;
		position: relative;
	}

	.picker-scroll {
		height: 100%;
	}

	.picker-item {
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		color: #666;
	}

	.picker-item.active {
		color: #333;
		font-weight: bold;
	}

	/* 城市选择器样式 */
	.city-picker-container {
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		overflow: hidden;
		max-height: 70vh;
	}

	.city-picker-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.city-picker-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.close-btn {
		width: 40rpx;
		height: 40rpx;
		background-color: #f5f5f5;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.city-picker-tabs {
		display: flex;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.tab-item {
		padding: 10rpx 20rpx;
		border-radius: 20rpx;
		background-color: #fff;
		border: 1rpx solid #ff4444;
	}

	.tab-item.active {
		background-color: #ff4444;
	}

	.tab-text {
		font-size: 24rpx;
		color: #ff4444;
	}

	.tab-item.active .tab-text {
		color: #fff;
	}

	.city-picker-content {
		display: flex;
		height: 400rpx;
	}

	.city-list {
		flex: 1;
		height: 100%;
	}

	.city-item {
		padding: 20rpx 30rpx;
		font-size: 28rpx;
		color: #333;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.city-item.active {
		color: #ff4444;
		background-color: #fff5f5;
	}

	.city-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.check-icon {
		display: flex;
		align-items: center;
	}

	/* 昵称编辑弹窗样式 */
	.nickname-edit-container {
		background-color: #fff;
		border-radius: 20rpx;
		width: 600rpx;
		overflow: hidden;
	}

	.nickname-edit-header {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
		position: relative;
	}

	.nickname-edit-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		text-align: center;
	}

	.nickname-edit-header .close-btn {
		position: absolute;
		right: 30rpx;
		top: 50%;
		transform: translateY(-50%);
	}

	.nickname-edit-content {
		padding: 30rpx;
	}

	.nickname-input {
		width: 100%;
		height: 80rpx;
		border: 2rpx solid #f0f0f0;
		border-radius: 10rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		color: #333;
		background-color: #fff;
	}

	.nickname-tip {
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
		display: block;
	}

	.nickname-edit-footer {
		display: flex;
		border-top: 1rpx solid #f0f0f0;
	}

	.nickname-btn {
		flex: 1;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.cancel-nickname-btn {
		border-right: 1rpx solid #f0f0f0;
	}

	.nickname-btn-text {
		font-size: 28rpx;
		color: #333;
	}

	.confirm-nickname-btn .nickname-btn-text {
		color: #ff4444;
	}
</style> 
